<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>One-to-Many Form</title>
    <style>
        h1 {
            font-size: 24px;
            color: #333;
            margin-bottom: 10px;
        }

        .item {
            margin-bottom: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            border-radius: 5px;
            background-color: #f2f2f2;
        }

        .quantities {
            margin-left: 20px;
        }

        label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
            font-size: 16px;
            color: #333;
        }

        input[type="text"],
        input[type="number"] {
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #ccc;
            margin-bottom: 10px;
            font-size: 16px;
            color: #333;
        }

        button {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
            font-size: 16px;
        }

        select {
            padding: 2px;
            background-color: white;
            color: #4CAF50;
            border: none;
            border-radius: 51px;
            cursor: pointer;
            margin-right: 10px;
            font-size: 20px;
        }

        button:hover {
            background-color: #3e8e41;
        }


        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 2rem;
            color: white;
        }

        .information {
            background-color: white;
            color: #3e8e41;
            box-shadow: 2px 2px 5px #888888;
            transition: transform 0.2s ease-in-out;
            transform: scale(0.9);

            padding: 10px;
            border-radius: 5px;
            font-size: 25px;

        }

        a {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
            font-size: 16px;
        }

    </style>

    <script src="/js/sweetalert2.all.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="css/sweetalert2.css"/>
</head>
<body>
<h1>当前连接状态</h1>
<div class="information">
    <div th:text="'连接地址为: ' + ${address}"></div>
    <div th:text="'数据库名为: ' + ${database}"></div>
    <a href="updateDataBase.html">修改</a>
    <button type="button" id="testConnect-button">测试连接</button>
</div>
</div>
<!--<div th:text="${'展示框'}">展示框</div>-->
<form id="databaseForm">
    <div id="items-container">
    </div>
    <button type="button" id="add-button">添加查询条件</button>
    <button type="submit" id="submit">生成</button>
    <button type="button" id="download-button">下载</button>
</form>
</body>

<script>
    // 页面不可操作状态
    const loadingOverlay = $('<div class="loading-overlay" >loading</div>');
    $('body').append(loadingOverlay);
    loadingOverlay.hide()

    $(function () {
        const itemsContainer = $('#items-container');
        const databaseForm = $('#databaseForm');
        let itemCount = 1;

        const createItemHtml = (itemCount) => `
            <div class="item">
                <label for="item-${itemCount}">数据库表名 ${itemCount}:</label>
                <input type="text" id="item-${itemCount}" name="items[${itemCount - 1}].tableName" required>
                <button type="button" class="delete-button">Delete</button>
                <button type="button" class="add-quantity-button">添加生成元素</button>
                <br>
                <div class="quantities-container">
                </div>
            </div>
        `;

        const createQuantityHtml = (itemCount, quantityCount) => `
            <div class="quantity">
                <label for="quantity-${itemCount}-${quantityCount}">形参:</label>
                    <input type="text" id="quantity-${itemCount}-${quantityCount}" name="items[${itemCount - 1}].quantities[${quantityCount - 1}].parameter" required>
                <br>
                <label for="compare-${itemCount}-${quantityCount}">比较类型:</label>
                <select id="compare-${itemCount}-${quantityCount}" name="items[${itemCount - 1}].quantities[${quantityCount - 1}].compareType" required>
                    <option value="A1" >eq(=)</option>
                    <option value="A2">like</option>
                    <option value="A3">startwith（like xxxx%）</option>
                    <option value="A4">endwith （like %xxxx）</option>
                    <option value="A5">containing（like %xxxx%"）</option>
                    <option value="A6">between</option>
                    <option value="A7">in</option>
                    <option value="A8">notin</option>
                    <option value="A9">ge（equal >=）</option>
                    <option value="A10">gt（than >）</option>
                    <option value="A11">le(equal <=)</option>
                    <option value="A12">lt（than <）</option>
                    <option value="A13">isNull(空)</option>
                    <option value="A14">isNotNull（非空）</option>
                    <option value="A15">not（不等于）</option>
                    <option value="A16">other</option>
                    <option value="A17">spellSql</option>
                </select>
                <br>
                <label for="data-${itemCount}-${quantityCount}">数据类型:</label>
                <select id="data-${itemCount}-${quantityCount}" name="items[${itemCount - 1}].quantities[${quantityCount - 1}].parameterType" required>
                    <option value="String">String</option>
                    <option value="Integer">Integer</option>
                    <option value="Boolean">Boolean</option>
                    <option value="Double">Double</option>
                    <option value="Float">Float</option>
                    <option value="BigDecimal">BigDecimal</option>
                    <option value="BigInteger">BigInteger</option>
                </select>
                <br>
                <label for="chinese-${itemCount}-${quantityCount}">中文释义:</label>
                <input type="text" id="chinese-${itemCount}-${quantityCount}" name="items[${itemCount - 1}].quantities[${quantityCount - 1}].parameterName" required>
                <br>
                <label for="db-${itemCount}-${quantityCount}">数据库对应类型:</label>
                <input type="text" id="db-${itemCount}-${quantityCount}" name="items[${itemCount - 1}].quantities[${quantityCount - 1}].dataBaseParam" required>
                <br>
                <br>
            </div>
        `;

        const addItem = () => {
            const itemHtml = createItemHtml(itemCount);
            itemsContainer.append(itemHtml);
            itemCount++;
        };
        //下载
        const downLoad = () => {
            window.location.href = '/api/tozip';
        }

        const isConnect = () => {
            $.ajax({
                type: 'get',
                url: '/api/isConnect',
                success: (response) => {
                    if (response.code == 0) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.msg
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'error',
                            text: response.msg,
                            footer: '<a href="updateDataBase.html">修改数据库</a>'

                        });
                        // window.location.href ="updateDataBase.html"
                    }
                },
                error: (xhr, status, error) => {
                    alert("Error: " + xhr.responseText);
                },
            })
        }

        const deleteItem = (event) => {
            $(event.target).parent().remove();
        };


        const addQuantity = (event) => {
            const $quantitiesContainer = $(event.target).siblings('.quantities-container');
            const quantityCount = $quantitiesContainer.children().length + 1;
            const quantityHtml = createQuantityHtml(itemCount, quantityCount);
            $quantitiesContainer.append(quantityHtml);
        };


        const showLoadingOverlay = () => {
            loadingOverlay.show();
        };

        const hideLoadingOverlay = () => {
            loadingOverlay.hide();
        };


        const submitForm = (event) => {
            event.preventDefault();

            const items = [];
            itemsContainer.find('.item').each(function () {
                const item = {
                    tableName: $(this).find('input[name$=".tableName"]').val(),
                    parametersDtoList: []
                };
                $(this).find('.quantity').each(function () {
                    const quantity = {
                        parameter: $(this).find('input[name$=".parameter"]').val(),
                        compareType: $(this).find('select[name$=".compareType"]').val(),
                        parameterType: $(this).find('select[name$=".parameterType"]').val(),
                        parameterName: $(this).find('input[name$=".parameterName"]').val(),
                        dataBaseParam: $(this).find('input[name$=".dataBaseParam"]').val()
                    };
                    item.parametersDtoList.push(quantity);
                });
                items.push(item);
            });
            console.log(items);


            $.ajax({
                type: 'POST',
                url: '/api/generate',
                data: JSON.stringify(items),
                contentType: 'application/json',
                dataType: 'json',
                beforeSend: showLoadingOverlay,
                // beforeSend: hideLoadingOverlay,
                success: (response) => {
                    if (response.code == 0) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.msg
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: '错误',
                            text: "生成成功部分代码生成失败" + response.msg
                        });
                    }
                },
                error: (xhr, status, error) => {
                    // alert("sasdasasd")
                    // console.log(xhr.responseText);
                    Swal.fire({
                        icon: 'Error',
                        title: 'Error',
                        text: response.msg
                    });
                },
                complete: hideLoadingOverlay
            });
        };


        $('#add-button').click(addItem);
        $("#download-button").click(downLoad);
        $("#testConnect-button").click(isConnect);
        itemsContainer.on('click', '.delete-button', deleteItem);
        itemsContainer.on('click', '.add-quantity-button', addQuantity);
        databaseForm.submit(submitForm);

    });
</script>
</html>